package org.jeecg.modules.basic.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.Wechat.controller.WeiXinService;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.bed.service.ILwgyBaseBedService;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.demo.student.service.ILwgyBaseStudentService;
import org.jeecg.modules.basic.entrance.entity.LwgyEntranceGuard;
import org.jeecg.modules.basic.entrance.service.ILwgyEntranceGuardService;
import org.jeecg.modules.basic.entry.service.ILwgyAbnormalActionService;
import org.jeecg.modules.basic.entry.service.ILwgyInoutRecordService;
import org.jeecg.modules.demo.qingjia.entity.LwgyQingJia;
import org.jeecg.modules.demo.qingjia.service.ILwgyQingJiaService;/*
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;*/
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author sn
 * @date 2022-09-23 15:20
 * 按照推送表的配置，推送信息。
 */
@Slf4j
public class AbnormalPushInfoJob implements Job {

    @Autowired
    private ILwgyEntranceGuardService lwgyEntranceGuardServic;
    @Autowired
    private ILwgyInoutRecordService lwgyInoutRecordService;
    @Autowired
    private ILwgyAbnormalActionService lwgyAbnormalActionService;
    @Autowired
    private ILwgyBaseBedService lwgyBaseBedService;
    @Autowired
    private ILwgyBaseStudentService lwgyBaseStudentService;
    @Autowired
    private ILwgyQingJiaService lwgyQingJiaService;

/*    @Autowired
    private ISysUserRoleService sysUserRoleService;*/



    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            log.info(String.format(" 时间:" + DateUtils.getTimestamp()));
            String dateFormat = DateUtils.now();
            List<LwgyEntranceGuard> list = lwgyEntranceGuardServic.list();
            if (oConvertUtils.isNotEmpty(list) && list.size() > 0) {
                for (LwgyEntranceGuard item : list) {

                    String pushType = item.getPushType();//推送类型 1 晚归，2未归，3异常 4在寝人数（按照楼宇） 5在寝室人数（按照学院）
                    String pushFunction = item.getPushFunction();////推送方式1短信2邮件3微信4系统,可能多项
                    String receiving = item.getReceiving();//接收人员角色 //角色id，待修改，用角色id 获取用户的openid 再关联推送给相应的人，目前写死给固定的用户 admin
                    List<Map<String, String>> userlist = lwgyEntranceGuardServic.getUserByRole(receiving); //接受人员的用户信息

                    System.out.println("userlist" + userlist);
                    System.out.println("userlist" + userlist.size());


                    if (pushType.equals("1")) {

                    } else if (pushType.equals("2")) {

                    } else if (pushType.equals("3")) {

                    } else if (pushType.equals("4")) {//4在寝人数（按照楼宇）
                        //如果是楼长就看自己楼，其余角色是查看全部，目前按照全部的查询
                        String htmUrl = "http://lwkjfw.cn/mobile/#/pages/houseChaxun/houseChaxun";
                        QueryWrapper<LwgyBaseStudent> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("student_state", "0");
                        queryWrapper.eq("student_delflag", "0");
                        List<LwgyBaseStudent> stulist = lwgyBaseStudentService.list(queryWrapper);
                        // 归寝和未归的计数
                        List<LwgyBaseStudent> inList = stulist.stream().filter(student -> student.getLastDirection().equals("1")).collect(Collectors.toList());
                        List<LwgyBaseStudent> outList = stulist.stream().filter(student -> student.getLastDirection().equals("2")).collect(Collectors.toList());

                        //请假计数
                        QueryWrapper<LwgyQingJia> QjqueryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("qing_state", "0");//没销假;
                        List<LwgyQingJia> qingJiaListlist = lwgyQingJiaService.list(QjqueryWrapper);


                        if (pushFunction.contains("1")) {
                        }//1短信
                        if (pushFunction.contains("2")) {
                        }//2邮件
                        if (pushFunction.contains("3")) {
                            String userOpenId = "";
                            if( userlist.size() >0 ){
                                for(Map<String, String> user :userlist){
                                    userOpenId += user.get("third_id") + ",";
                                }
                                if(oConvertUtils.isNotEmpty(userOpenId)){
                                    userOpenId = userOpenId.substring(0,userOpenId.length()-1);
                                }else{
                                    userOpenId ="ogie6wQZeoyZJCcWhHU5xlt5ddfg";//孙娜固定的那个
                                }
                            }
                            WeiXinService wx = new WeiXinService();
                            wx.sendStuDormitoryByWeiXin("在寝人数数据按楼宇分布：", "在寝人数按楼宇分布，点击查看详情", "目前在宿 " + inList.size() + "人，未返 " + outList.size() + "人，请假 " + qingJiaListlist.size() + "人，实习 0人。", dateFormat, "点击详情并及时处理", htmUrl,userOpenId);
                        }//3微信
                        if (pushFunction.contains("4")) {
                        }//4系统


                    } else if (pushType.equals("5")) {
                        //5在寝室人数（按照学院）
                        //如果是辅导员就看自己学院，其余角色是查看全部，目前按照全部的查询
                        String htmUrl = "http://lwkjfw.cn/mobile/#/pages/schoolChaxun/schoolChaxun";
                        QueryWrapper<LwgyBaseStudent> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("student_state", "0");
                        queryWrapper.eq("student_delflag", "0");
                        List<LwgyBaseStudent> stulist = lwgyBaseStudentService.list(queryWrapper);
                        // 归寝和未归的计数
                        List<LwgyBaseStudent> inList = stulist.stream().filter(student -> student.getLastDirection().equals("1")).collect(Collectors.toList());
                        List<LwgyBaseStudent> outList = stulist.stream().filter(student -> student.getLastDirection().equals("2")).collect(Collectors.toList());

                        //请假计数
                        QueryWrapper<LwgyQingJia> QjqueryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("qing_state", "0");//没销假;
                        List<LwgyQingJia> qingJiaListlist = lwgyQingJiaService.list(QjqueryWrapper);

                        if (pushFunction.contains("1")) {
                        }//1短信
                        if (pushFunction.contains("2")) {
                        }//2邮件
                        if (pushFunction.contains("3")) {
                            String userOpenId = "";
                            if( userlist.size() >0 ){
                                for(Map<String, String> user :userlist){
                                    userOpenId += user.get("third_id") + ",";
                                }
                                if(oConvertUtils.isNotEmpty(userOpenId)){
                                    userOpenId = userOpenId.substring(0,userOpenId.length()-1);
                                }else{
                                    userOpenId ="ogie6wQZeoyZJCcWhHU5xlt5ddfg";//孙娜固定的那个
                                }
                            }

                            WeiXinService wx = new WeiXinService();
                            wx.sendStuDormitoryByWeiXin("在寝人数数据按学院分布：", "在寝人数按学院分布，点击查看详情", "目前在宿 " + inList.size() + "人，未返 " + outList.size() + "人，请假 " + qingJiaListlist.size() + "人，实习 0人。", dateFormat, "点击详情并及时处理", htmUrl,userOpenId);
                        }//3微信
                        if (pushFunction.contains("4")) {
                        }//4系统
                    }

                }
            }
        }catch(Exception e){}
    }

}


        //晚归的pushtype好像1
       /* List<LwgyEntranceGuard> checkList = list.stream().filter(item ->
                item.getPushType().equals("1")).collect(Collectors.toList());
        if(oConvertUtils.isNotEmpty(checkList) && checkList.size()>0){
            //存在晚归的设置，可以进行推送
            LwgyEntranceGuard map = (LwgyEntranceGuard) checkList.get(0);
            String entranceTime = map.getEntranceTime();//超过这个时间的就算晚归
            if(oConvertUtils.isEmpty(entranceTime)){
                entranceTime="22:00";//没设置时间按照晚上十点算
            }
            String dateFormat =DateUtils.now();
            System.out.println("今天时间"+dateFormat);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化时间格式
            Date date = new Date(); //当前时间
            Calendar calendar = Calendar.getInstance(); //得到日历
            calendar.setTime(date);//把当前时间赋给日历
            calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
            String beforeOneDay = sdf.format(calendar.getTime()); //得到前一天的时间
            String endTime = beforeOneDay.substring(0, 10) + " "+entranceTime+":00";
            System.out.println("endTime:"+endTime);
            QueryWrapper<LwgyInoutRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("direction", "1");
            queryWrapper.between("record_date",endTime,dateFormat);//进入时间小于当前时间，//晚于今天前一天的最晚时间，算晚归
            List<LwgyInoutRecord> wglist = lwgyInoutRecordService.list(queryWrapper);//---=====  关联查询xy,bed 等信息，一起保存
            //循环wglist ,写入异常表
            if(wglist.size()>0){
                //通过晚归信息，获取里面学生id.从而获取相应的学院和bed
                String[] numbers = wglist.stream().map(p -> p.getUserId()).collect(Collectors.toList()).toArray(new String[0]);
                //通过学号获取所有的学生信息，包括学生ｉｄ，学院专业等

                //通过学生id获取原床位信息
                List<LwgyBaseStudent> stuList = lwgyBaseStudentService.getStuListByStuNumber(numbers);
                String[] ids = stuList.stream().map(p -> p.getId()).collect(Collectors.toList()).toArray(new String[0]);
                List<LwgyBaseBed> bedList = lwgyBaseBedService.getBedListByStuId(ids);
                //获取学院信息床位信息end
                List<LwgyAbnormalAction> endList = new ArrayList<LwgyAbnormalAction>();
                wglist.stream().forEach(item->{

                    LwgyAbnormalAction lwgyAbnormalAction = new LwgyAbnormalAction();
                    List<LwgyBaseStudent> studentList = stuList.stream().filter(p -> p.getStudentNumber().equals(item.getUserId())).collect(Collectors.toList());
                    if(oConvertUtils.isNotEmpty(studentList) && studentList.size()>0 ){
                        LwgyBaseStudent lwgyBaseStudent = studentList.get(0);
                        lwgyAbnormalAction.setStudentid(lwgyBaseStudent.getId());
                        lwgyAbnormalAction.setStudentXy(lwgyBaseStudent.getStudentCollege());
                        lwgyAbnormalAction.setStudentZy(lwgyBaseStudent.getStudentMajor());
                        lwgyAbnormalAction.setStudentBj(lwgyBaseStudent.getStudentClass());
                        lwgyAbnormalAction.setStudentSex(lwgyBaseStudent.getStudentSex());
                        List<LwgyBaseBed> bedsList = bedList.stream().filter(d -> d.getStudentId().equals(lwgyBaseStudent.getId())).collect(Collectors.toList());
                        if(oConvertUtils.isNotEmpty(bedsList)  && bedsList.size()>0){
                            LwgyBaseBed lwgyBaseBed = bedsList.get(0);
                            lwgyAbnormalAction.setCampus(lwgyBaseBed.getCampusId());
                            lwgyAbnormalAction.setBuildingNum(lwgyBaseBed.getBuildingId());
                            lwgyAbnormalAction.setUnit(lwgyBaseBed.getUnitId());
                            lwgyAbnormalAction.setRoomNum(lwgyBaseBed.getRoomId());
                            lwgyAbnormalAction.setBedNum(lwgyBaseBed.getId());
                        }

                    }
                    lwgyAbnormalAction.setStuStatus("1");//晚归
                    lwgyAbnormalAction.setStudentName(item.getUserName());
                    lwgyAbnormalAction.setStudentNumber(item.getUserId());
                    lwgyAbnormalAction.setLastIntoStatus(item.getDirection());
                    lwgyAbnormalAction.setLastIntoTime(item.getRecordDate());
                    endList.add(lwgyAbnormalAction);
                    });
                lwgyAbnormalActionService.saveBatch(endList);*/
/*
            }
        }*/
